// 弹出界面的交互逻辑

// 当前域名
let currentDomain = '';
// 当前域名的配置
let currentDomainConfig = null;
// 所有域名的配置
let allDomainConfigs = {};

// DOM元素
const domainElement = document.getElementById('current-domain');
const selectorsContainer = document.getElementById('selectors-container');
const addSelectorButton = document.getElementById('add-selector');
const saveConfigButton = document.getElementById('save-config');
const deleteConfigButton = document.getElementById('delete-config');
const domainListElement = document.getElementById('domain-list');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  // 获取当前标签页的域名
  getCurrentDomain();
  
  // 加载所有域名配置
  loadAllDomainConfigs();
  
  // 添加事件监听器
  addSelectorButton.addEventListener('click', addSelectorField);
  saveConfigButton.addEventListener('click', saveCurrentConfig);
  deleteConfigButton.addEventListener('click', deleteCurrentConfig);
});

// 获取当前标签页的域名
function getCurrentDomain() {
  chrome.runtime.sendMessage({action: 'getCurrentUrl'}, (response) => {
    if (response && response.hostname) {
      currentDomain = response.hostname;
      domainElement.textContent = currentDomain;
      
      // 加载当前域名的配置
      loadCurrentDomainConfig();
    } else {
      domainElement.textContent = '无法获取域名';
    }
  });
}

// 加载所有域名配置
function loadAllDomainConfigs() {
  chrome.storage.sync.get(['domainConfigs'], (result) => {
    allDomainConfigs = result.domainConfigs || {};
    updateDomainList();
  });
}

// 加载当前域名的配置
function loadCurrentDomainConfig() {
  chrome.storage.sync.get(['domainConfigs'], (result) => {
    const domainConfigs = result.domainConfigs || {};
    currentDomainConfig = domainConfigs[currentDomain] || { inputSelectors: [] };
    
    // 更新UI
    updateSelectorsUI();
  });
}

// 更新选择器UI
function updateSelectorsUI() {
  // 清空容器
  selectorsContainer.innerHTML = '';
  
  // 如果没有选择器，添加一个空的
  if (!currentDomainConfig.inputSelectors || currentDomainConfig.inputSelectors.length === 0) {
    addSelectorField();
    return;
  }
  
  // 添加现有的选择器
  currentDomainConfig.inputSelectors.forEach((selector, index) => {
    addSelectorField(selector);
  });
}

// 添加选择器字段
function addSelectorField(selectorConfig = { selector: '', value: '', delay: 0 }) {
  const selectorDiv = document.createElement('div');
  selectorDiv.className = 'selector-item';
  
  selectorDiv.innerHTML = `
    <div class="form-group">
      <label>选择器 (CSS):</label>
      <input type="text" class="selector-input" value="${selectorConfig.selector}" placeholder="例如: #username, .input-field">
    </div>
    <div class="form-group">
      <label>填充值:</label>
      <input type="text" class="value-input" value="${selectorConfig.value}" placeholder="要填充的内容">
    </div>
    <div class="form-group">
      <label>延迟 (毫秒):</label>
      <input type="number" class="delay-input" value="${selectorConfig.delay}" min="0" step="100">
    </div>
    <button class="btn remove-selector">删除</button>
  `;
  
  // 添加删除按钮事件
  const removeButton = selectorDiv.querySelector('.remove-selector');
  removeButton.addEventListener('click', () => {
    selectorDiv.remove();
  });
  
  // 添加到容器
  selectorsContainer.appendChild(selectorDiv);
}

// 从UI收集当前配置
function collectCurrentConfig() {
  const selectorItems = selectorsContainer.querySelectorAll('.selector-item');
  const inputSelectors = [];
  
  selectorItems.forEach(item => {
    const selector = item.querySelector('.selector-input').value.trim();
    const value = item.querySelector('.value-input').value;
    const delay = parseInt(item.querySelector('.delay-input').value) || 0;
    
    if (selector) {
      inputSelectors.push({ selector, value, delay });
    }
  });
  
  return { inputSelectors };
}

// 保存当前配置
function saveCurrentConfig() {
  if (!currentDomain) {
    alert('无法获取当前域名');
    return;
  }
  
  // 收集当前配置
  const config = collectCurrentConfig();
  
  // 如果没有有效的选择器，提示用户
  if (config.inputSelectors.length === 0) {
    alert('请至少添加一个有效的选择器');
    return;
  }
  
  // 更新配置
  allDomainConfigs[currentDomain] = config;
  
  // 保存到存储
  chrome.storage.sync.set({ domainConfigs: allDomainConfigs }, () => {
    alert('配置已保存');
    updateDomainList();
  });
}

// 删除当前配置
function deleteCurrentConfig() {
  if (!currentDomain || !allDomainConfigs[currentDomain]) {
    alert('当前域名没有配置');
    return;
  }
  
  if (confirm(`确定要删除 ${currentDomain} 的配置吗？`)) {
    // 删除配置
    delete allDomainConfigs[currentDomain];
    
    // 保存到存储
    chrome.storage.sync.set({ domainConfigs: allDomainConfigs }, () => {
      alert('配置已删除');
      updateDomainList();
      
      // 重置当前配置
      currentDomainConfig = { inputSelectors: [] };
      updateSelectorsUI();
    });
  }
}

// 更新域名列表
function updateDomainList() {
  // 清空列表
  domainListElement.innerHTML = '';
  
  // 添加域名
  const domains = Object.keys(allDomainConfigs);
  
  if (domains.length === 0) {
    const li = document.createElement('li');
    li.textContent = '暂无配置';
    domainListElement.appendChild(li);
    return;
  }
  
  domains.forEach(domain => {
    const li = document.createElement('li');
    li.textContent = domain;
    
    // 点击加载该域名的配置
    li.addEventListener('click', () => {
      currentDomain = domain;
      domainElement.textContent = currentDomain;
      currentDomainConfig = allDomainConfigs[domain];
      updateSelectorsUI();
    });
    
    domainListElement.appendChild(li);
  });
}